package com.sc.nft.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.log4j.Log4j;

import java.lang.reflect.Field;

public class EncryptionUtil {
    private static final String KEY = "metago@2024@wallet-chain"; // 16位密钥

    /**
     * 单个加密
     * @param obj
     * @throws IllegalAccessException
     */
    public static void encryptObject(Object obj) throws IllegalAccessException {
        AES aes = SecureUtil.aes(KEY.getBytes());
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType() == String.class) {
                field.setAccessible(true);
                String originalValue = (String) field.get(obj);
                if (StrUtil.isNotBlank(originalValue)) {
                    String encryptedValue = aes.encryptHex(originalValue);
                    field.set(obj, encryptedValue);
                }
            }
        }
    }

    /**
     * 单个解密
     * @param obj
     * @throws IllegalAccessException
     */
    public static void decryptObject(Object obj) throws IllegalAccessException {
        AES aes = SecureUtil.aes(KEY.getBytes());
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType() == String.class) {
                field.setAccessible(true);
                String encryptedValue = (String) field.get(obj);
                if (StrUtil.isNotBlank(encryptedValue)) {
                    String decryptedValue = aes.decryptStr(encryptedValue);
                    field.set(obj, decryptedValue);
                }
            }
        }
    }

    /**
     * 单个解密
     * @param jsonArray
     */
    public static void decryptJSONArray(JSONArray jsonArray) {
        AES aes = SecureUtil.aes(KEY.getBytes());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            for (String key : jsonObject.keySet()) {
                String encryptedValue = jsonObject.getStr(key);
                if (StrUtil.isNotBlank(encryptedValue)) {
                    String decryptedValue = aes.decryptStr(encryptedValue);
                    jsonObject.set(key, decryptedValue);
                }
            }
        }
    }
}
